package com.heima.comment.service.impl;

import com.heima.comment.service.ICommentHotService;
import com.heima.model.comment.pojos.ApComment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class CommentHotService implements ICommentHotService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 将普通评论晋升为热评
     * @param apComment
     */
    @Override
    @Async
    public void hotCommentExecutor(ApComment apComment) {
        /*查询热门评论列表*/
        List<ApComment> hotCommentList = mongoTemplate.find(Query.query(Criteria.where("article_id").is(apComment.getArticleId()).and("flag").is(1)).with(Sort.by(Sort.Direction.DESC, "likes")), ApComment.class);
        //1.判断当前文章的热门评论是否大于等于 5 条
        if(hotCommentList == null || hotCommentList.size() < 5){
            //1.1否，当前评论直接晋升为热门评论
            apComment.setFlag((short) 1);
            mongoTemplate.save(apComment);
            return;
        }
        //2.是，判断当前评论的点赞数是否大于热门评论中最后一条评论的点赞数
        if(apComment.getLikes() > hotCommentList.get(hotCommentList.size() - 1).getLikes()){
            //2.1是，热门评论中最后一条评论降级为普通评论，当前评论晋升为热门评论
            ApComment lastHotComment = hotCommentList.get(hotCommentList.size() - 1);
            lastHotComment.setFlag((short) 0);
            mongoTemplate.save(lastHotComment);

            apComment.setFlag((short) 1);
            mongoTemplate.save(apComment);
            return;
        }
        return;
    }
}
